import React from 'react';
import PropTypes from 'prop-types';
import {Spin, Card, Button, Row, Col, Table} from 'antd';
import {DATE_FORMAT, FILES_API, TABLE} from '../constants';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import routes from './routes';
import {abandonData, cancelData, getDetail, getPiExcel} from './api';
import {injectIntl} from './intl';
import {currency, saleOrderPriceTerms, paymentType, saleOrderTransportTypeForKd} from '../Enum';
import {conventEnumValueToString, formatDateTime, formatAmount, exportDownload} from '../utils';
import {hasPermissions} from './utils';
import {PERMISSION, formatPrintPdfUrl} from './constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
const {Description} = DescriptionList;
export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
        data: {},
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        subPIPlacements: res.data.subPIPlacements,
                        subPIDetails: res.data.subPIDetails.map(d => Object.assign({}, d, {
                            order: res.data.subPIDetails.findIndex(x => x.id === d.id) + 1,
                        })),
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    handleUpdateClick = () => {
        this.props.history.push(routes.update.format(this.props.id));
    }
    handleConfirmClick = () => {
        this.props.history.push(routes.confirm.format(this.props.id));
    }
    onClickAbandonBtn = () => {
        this.setState({loading: true});
        abandonData(this.state.data.id, this.state.data.rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickCancelBtn = () => {
        this.setState({loading: true});
        cancelData(this.state.data.id, this.state.data.rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onExportExcel = e => {
        this.setState({
            loading: true
        });
        getPiExcel(e.currentTarget.dataset.id).then(res => {
            this.setState({
                loading: false
            });
            exportDownload(res);
        });
    }
    onExportPdf = e => {
        e.stopPropagation();
        window.open(formatPrintPdfUrl(e.currentTarget.dataset.id, e.currentTarget.dataset.code));
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, subPIPlacements, subPIDetails} = this.state;
        let totalAmount = 0;
        let totalQuantity = 0;
        let totalAmountSum = 0;
        let totalQuantitySum = 0;
        if(subPIDetails)
            subPIDetails.forEach(v => {
                totalAmount += ((v.quantity ? v.quantity : 0) * (v.price ? v.price : 0));
                totalQuantity += v.quantity;
            });
        if(subPIPlacements)
            subPIPlacements.forEach(v => {
                totalAmountSum += ((v.quantity ? v.quantity : 0) * (v.price ? v.price : 0));
                totalQuantitySum += v.quantity;
            });
        const operations = [];
        const columns = [{
            title: formatMessage({
                id: 'newPanel.column.placement',
                defaultMessage: '配置'
            }),
            dataIndex: 'placement',
        }, {
            title: formatMessage({
                id: 'newPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity',
        }, {
            title: formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.amount',
                defaultMessage: '金额'
            }),
            dataIndex: 'amount',
            render: (text, record) => formatAmount((record.price) * (record.quantity))
        }, {
            title: formatMessage({
                id: 'newPanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
        }];
        const partColumns = [{
            title: formatMessage({
                id: 'newPanel.column.order',
                defaultMessage: '序号'
            }),
            dataIndex: 'order',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partNameInChinese',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partNameInChinese',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partNameInEnglish',
                defaultMessage: '备件英文名称'
            }),
            dataIndex: 'partNameInEnglish',
        }, {
            title: formatMessage({
                id: 'newPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity',
        }, {
            title: formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.amount',
                defaultMessage: '金额'
            }),
            dataIndex: 'amount',
            render: (text, record) => formatAmount((record.price) * (record.quantity))
        }, {
            title: formatMessage({
                id: 'newPanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
        }];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" onClick={this.handleUpdateClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.update',
                    defaultMessage: '修改'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickAbandonBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.btn.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.cancel) && hasPermissions(data.options, PERMISSION.cancel))
            operations.push(<WrappedPopconfirm
                key="cancel"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickCancelBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.cancel',
                    defaultMessage: '是否确认取消Sub PI？'
                })}>
                <Button key="cancel" size="small">{
                    formatMessage({
                        id: 'detailPanel.btn.cancel',
                        defaultMessage: '取消Sub PI'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.confirm) && hasPermissions(data.options, PERMISSION.confirm))
            operations.push(<Button key="confirm" onClick={this.handleConfirmClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.confirm',
                    defaultMessage: '确认'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.exportExcel) && hasPermissions(data.options, PERMISSION.exportExcel))
            operations.push(<Button key="exportExcel" data-id={this.props.id} onClick={this.onExportExcel} size="small">{
                formatMessage({
                    id: 'detailPage.btn.exportExcel',
                    defaultMessage: '下载Excel'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.exportPdf) && hasPermissions(data.options, PERMISSION.exportPdf))
            operations.push(<Button key="exportPdf" data-id={this.props.id} data-code={this.props.code} onClick={this.onExportPdf} size="small">{
                formatMessage({
                    id: 'detailPage.btn.exportPdf',
                    defaultMessage: '下载Pdf'
                })
            }</Button>);
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={12}>{formatMessage({
                            id: 'detailPanel.text.title',
                            defaultMessage: '基本信息'
                        })}</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={12}>{operations}</Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.brand',
                                defaultMessage: '品牌'
                            })}>{`(${data.brandCode})${data.brandName}`}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.dealerCode',
                                defaultMessage: '总代编号'
                            })}>{data.dealerCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.batchNumber',
                                defaultMessage: '批次号'
                            })}>{data.batchNumber}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.piCode',
                                defaultMessage: '发票号'
                            })}>{data.piCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.productionMonth',
                                defaultMessage: '产品月份'
                            })}>{data.productionMonth}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.title2',
                                defaultMessage: '标题'
                            })}>{data.title}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.cargoDescription',
                                defaultMessage: '货描'
                            })}>{data.cargoDescription}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.model',
                                defaultMessage: '车型编号'
                            })}>{data.model}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.supplierName',
                                defaultMessage: '供应商名称'
                            })}>{data.supplierName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, data.currency)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.tradeMethodName',
                                defaultMessage: '贸易方式'
                            })}>{data.tradeMethodName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.salesOrderPriceTerms',
                                defaultMessage: '价格条款'
                            })}>{conventEnumValueToString(saleOrderPriceTerms, data.salesOrderPriceTerms)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.paymentType',
                                defaultMessage: '付款方式'
                            })}>{conventEnumValueToString(paymentType, data.paymentType)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.productAmount',
                                defaultMessage: '备件总金额'
                            })}>{formatAmount(data.productAmount)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.typeAmount',
                                defaultMessage: '货物总金额'
                            })}>{formatAmount(data.typeAmount)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.deliveryTerms',
                                defaultMessage: '运输方式'
                            })}>{conventEnumValueToString(saleOrderTransportTypeForKd, data.deliveryTerms)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.shippingPortName',
                                defaultMessage: '发运港口'
                            })}>{data.shippingPortName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.destinationPort',
                                defaultMessage: '目的港口'
                            })}>{data.destinationPort}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.bankAccount',
                                defaultMessage: '银行账号'
                            })}>{data.bankAccount}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.bankName',
                                defaultMessage: '银行名称'
                            })}>{data.bankName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.bankNameEng',
                                defaultMessage: '银行英文名称'
                            })}>{data.bankNameEng}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.swift',
                                defaultMessage: '银行识别码'
                            })}>{data.swift}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.bankAccount',
                                defaultMessage: '银行账号'
                            })}>{data.bankAccount}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.createTime',
                                defaultMessage: '提报日期'
                            })}>{formatDateTime(data.createTime, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.creatorName',
                                defaultMessage: '创建人姓名'
                            })}>{data.creatorName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.remark',
                                defaultMessage: '备注'
                            })}>{data.remark}</Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.details',
                            defaultMessage: 'Sub PI配置清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="id"
                                pagination={false}
                                dataSource={subPIPlacements}
                                footer={() => <DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalQuantity',
                                        defaultMessage: '数量汇总'
                                    })}>{totalQuantitySum ? totalQuantitySum : null}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalAmount',
                                        defaultMessage: '金额汇总'
                                    })}>{formatAmount(totalAmountSum ? totalAmountSum : null)}
                                    </Description>
                                </DescriptionList>}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.subPIDetails',
                            defaultMessage: 'Sub PI清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={partColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={subPIDetails}
                                footer={() => <DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalQuantity',
                                        defaultMessage: '数量汇总'
                                    })}>{totalQuantity ? totalQuantity : null}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalAmount',
                                        defaultMessage: '金额汇总'
                                    })}>{formatAmount(totalAmount ? totalAmount : null)}
                                    </Description>
                                </DescriptionList>}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card>
                        {data.attachments && data.attachments.length >= 0
                            ? <DescriptionList size="large" title={formatMessage({
                                id: 'detailPanel.card.attachments',
                                defaultMessage: 'Sub PI附件'
                            })}>
                                {data.attachments.map(item => (<Description key={item.fileId}>
                                    <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                        {item.fileName}</a></Description>))}
                            </DescriptionList>
                            : <DescriptionList title={formatMessage({
                                id: 'detailPanel.content.noAttachment',
                                defaultMessage: '暂无附件'
                            })}>
                            </DescriptionList>}
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.state.loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'detailPage.text.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    id: PropTypes.string.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    successReturn: PropTypes.func,
};

import {connect} from 'react-redux';
import {
    tableSearch
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);

const mapStateToProps = (state, props) => ({
    id: props.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
